import React from 'react'
import Moment from 'react-moment'
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native'
import { withNavigation } from 'react-navigation'
import { last } from 'lodash'
import { Avatar } from './avatar'

export const defaultChatName = (chat, self) =>
  (ns => ns.join(', '))(
    chat.members.filter(x => x.id !== self.id).map(x => x.name),
  )

export const ChatItem = withNavigation(({ chat, self, navigation }) => (
  <TouchableOpacity
    style={styles.container}
    onPress={() => navigation.navigate('Chat', { id: chat.id })}
  >
    <View style={styles.avatar}>
      <Avatar size={50} />
    </View>
    <View style={styles.wrapper}>
      <View style={styles.header}>
        <Text style={styles.name}>
          {chat.name || defaultChatName(chat, self)}
        </Text>
        <Text style={styles.time}>
          <Moment calendar>{(last(chat.messages) || {}).createdAt}</Moment>
        </Text>
      </View>
      <Text style={styles.content}>{(last(chat.messages) || {}).content}</Text>
    </View>
  </TouchableOpacity>
))

const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1,
    borderBottomColor: 'whitesmoke',
  },
  avatar: {
    margin: 10,
  },
  wrapper: {
    flex: 1,
    marginVertical: 15,
    justifyContent: 'center',
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  name: {
    fontSize: 15,
    marginBottom: 5,
  },
  time: {
    fontSize: 12,
    marginRight: 15,
    color: 'slategray',
  },
  content: {
    fontSize: 12.5,
    color: 'slategray',
  },
})
